package dao

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"time"
)

type Menu struct {
	Mid int `json:"m_id" gorm:"column:m_id"`
	Fid int `json:"f_id" gorm:"column:f_id"`
	Name string `json:"name" gorm:"column:name"`
	Icon string `json:"icon" gorm:"column:icon"`
	Desc string `json:"desc" gorm:"column:desc"`
	Path string `json:"path" gorm:"column:path"`
	BaseModel
	Children []*Menu `json:"children"`
}
func (t *Menu)Create(d map[string]interface{}) (bool,int) {
	var ma Menu
	ma.Mid = 0
	if v,ok := d["f_id"];ok{
		ma.Fid = v.(int)
	}
	if v,ok := d["name"];ok{
		ma.Name = v.(string)
	}
	if v,ok := d["icon"];ok{
		ma.Icon = v.(string)
	}
	if v,ok := d["desc"];ok{
		ma.Desc = v.(string)
	}
	if v,ok := d["path"];ok{
		ma.Path = v.(string)
	}
	ma.Ctime = XTime{
		time.Now(),
	}
	err := db.Create(&ma).Error

	b := true
	if err != nil{
		b = false
	}

	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return b,id[0]

}
/**
	软删除
 */
func (t *Menu)Delete(w map[string]interface{}) bool {

	err := db.Model(&t).Where(w).Update("d_time",time.Now()).Error
	b := true
	if err != nil {
		b = false
	}
	return b
}
func (t *Menu)Update(w map[string]interface{},f map[string]interface{}) bool {

	if v,ok := f["f_id"];ok{
		t.Fid = v.(int)
	}
	if v,ok := f["name"];ok{
		t.Name = v.(string)
	}
	if v,ok := f["icon"];ok{
		t.Icon = v.(string)
	}
	if v,ok := f["desc"];ok{
		t.Desc = v.(string)
	}
	if v,ok := f["path"];ok{
		t.Path = v.(string)
	}
	err := db.Model(&t).Where(w).Updates(f).Error
	b := true
	if err != nil{
		b = false
	}
	return b

}
func (t *Menu)Find(w map[string]interface{},page int64,pageSize int64)([]*Menu,int,error){

	var total int = 0
	var rs []*Menu
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).
		Where("d_time is NULL").
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("m_id desc").Find(&rs).Error

	// 获取总条数
	db.Model(&t).Where(w).Where("d_time is NULl").Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return rs,total,nil

}
func (t *Menu) Nodes() []*Menu {

	var rs []*Menu
	err := db.Where("d_time is NULl").Order("m_id desc").Find(&rs).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return nil
	}
	return rs
}
func (t *Menu)First(w map[string]interface{}) (bool,*Menu) {
	err := db.
		Where("d_time is NULl").
		Where(w).First(&t).Error

	if err !=nil{
		fmt.Println(err)
		return false,nil
	}
	return true,t
}

func (mt *Menu)Trees(fid int, d []*Menu) []*Menu{

	treeList := []*Menu{}

	if d != nil{

		for _,v := range d{
			node := &Menu{
				Mid:v.Mid,
				Fid:v.Fid,
				Name:v.Name,
				Desc:v.Desc,
				Path:v.Path,
				Icon:v.Icon,
				//Ctime:v.Ctime,
				//Dtime:v.Dtime,
				BaseModel:BaseModel{Ctime: v.Ctime},
			}

			if v.Fid == fid{
				node.Children = mt.Trees(v.Mid,d)
				treeList = append(treeList,node)
			}
		}
	}
	return treeList

}
var MenuDao = &Menu{}